<?php

namespace app\controllers;

use app\models\BlxbgameMorningRecord;
use Yii;
use app\controllers\basecommon\BaseController;
use app\models\BlxbgameUser;
use app\models\BlxbgameMorning;

class MorningController extends BaseController
{
    public function actionIndex()
    {
        //$log_content = "修改morning表(起床总表)失败，无法修改起床时间，连续签到时间|用户信息：";

        //Yii::warning($log_content);
        //return $this->render('index');
        //$userInfo['openid'] = 'ouof80FS1RePzeCpUAB28s5BYT48';
       //echo "123";
       // var_dump($this->actionGetuserinfo($userInfo));
        //var_dump(YII::$app->params['Switch']['Breakfast']);
        //var_dump(BlxbgameMorning::LastTenbydatatime());
        //$this->actionWakeup($userInfo);
    }

    //缓存的执行 还有日志的记录

    /**
     * @param $getInfo['openid] 用户的openid
     * post 过来的
     */
    //当用户点击起床按钮时，数据的处理
    //加签到失败
    public function actionWakeup(){

        if(!YII::$app->params['Switch']['WakeUp']){


            $this->renderJSON('北鼻，起床争霸赛已经结束了哦');
            die;
        }

        date_default_timezone_set('Asia/Shanghai');
        $getInfo = Yii::$app->request->post();
      
       
        //1.获取用户起床信息 $getInfo['id']
        $userInfo = $this->SearchInfoByOpenid($getInfo['openid']);
        $morningResult = BlxbgameMorning::data_by_id($userInfo['id']);
        $content = "";
        //2.检查当天是否已经签到
            if($this->wakeUpSign($morningResult))
            {
                //$this->renderJSON('北鼻，今天你已经签到了');
                $content = "北鼻，今天你已经签到了\n\n";
                //当天已经签到 返回签到标语
            }

        //3.判断当前时间，非规定时间返回文字，规定时间继续
        // $time = $this->judgeTime();
        // if($time)
        // {
        //     $this->renderJSON($time);
        // }
       ///4.计算 判断是不是第一次使用，连续签到天数，总分
            $confirmData =  $this->confirmSignUp($morningResult);
        //5.签到的具体时间精确到毫秒
        $msecTime = (string)$this -> getmsecTime();
        //6.根据情况选择（第一次）插入还是修改
        //$msecTime,$confirmData['totalscore'],$confirmData['signdays']
        $data = array(
            'time'=> date ( "Y-m-d H:i:s"),
            'userid'=> $userInfo['id'],
            'msectime'=> $msecTime,
            'totalscore'=>$confirmData['totalscore'],
            'signdays'=>$confirmData['signdays'],
        );
        //$data =  serialize($data);
        //var_dump($data);
        if($this->wakeUpSign($morningResult))
        {
            $this->WakeUpContent($getInfo, $content);
        }else {

           if( BlxbgameMorning::saveData($data) && BlxbgameMorningRecord::addMorningRecord($userInfo)) {
              //7.插入起床记录
              $this->WakeUpContent($getInfo, $content);
           }else {
            $content = "签到失败,后台@留言,联系‘北理小报’~";
             $this->renderJSON($content);
           }
           
            //var_dump(BlxbgameMorningRecord::addMorningRecord($userInfo));
           
            
        }
    }


    //点击起床后，返回用户文字的签到
    public function WakeUpContent($getInfo,$alreadyWake=""){
        date_default_timezone_set('Asia/Shanghai');
        //1.获取用户起床信息
        $userInfo = $this->SearchInfoByOpenid($getInfo['openid']);
        $morningResult = BlxbgameMorning::data_by_id($userInfo['id']);
        //var_dump($morningResult);
        //2.处理还没有在morning表有数据
        //用时间 和 mesctime 来寻找排名
        if(!$morningResult){
            $morningResult['time'] = 0;
            $morningResult['msectime'] = 0;
        }

        //$this->renderJSON($morningResult);
        //die;

        //3.检查当天是否已经签到
        //$this -> wakeUpContentSign($morningResult);
        //4.获取用户起床,积分排名
        $morningRank = $this->getMorningRank($morningResult['time'],$morningResult['msectime']);
        $totalscoreRank = $this->getTotalScoreRank($morningResult['totalscore'],$morningResult['time'],$morningResult['msectime']);
        $YMDHISTime = date ( 'Y-m-d H:i:s' );
        //5.组装文字
        if($alreadyWake == null) {
            $title = "北鼻，你已成功开启起床系统\n\n";
            $content = $title . "你是今天第" . $morningRank . "个起床的北鼻哦.\n\n";
        }
        else{
            $title = $alreadyWake;
            $content = $title . "你是今天第" . $morningRank . "个起床的北鼻哦.\n\n";
        }
        //6.查询是否获奖 开关 周末 排名是否前10
        //早餐
        //var_dump($this->judgeWeekend());
            if( YII::$app->params['Switch']['Breakfast'] && $this->judgeWeekend() && $morningRank <= 10 ){
                //当前十并且 星期1-5 且 开关为开
                $content = $content."获得由【北理小报】赞助的早餐一份.\n请在今天7:30-9:00到【鑫茂汤包王】（在农行营业厅旁）领取.(需要提供当天签到记录).\n\n";
            }

        $content = $content."\n到".$YMDHISTime."为止,\n已经连续签到".$morningResult['signdays']."天,\n积分共有:".$morningResult['totalscore']."分,\n积分排名:".$totalscoreRank."名.\n";
        $this->renderJSON($content);
    }

    /**
     * [判断当前时间]
     * @param  [array] $userResult [用户基本信息]
     * @return
     * 			在规定范围    直接返回
     * 			不在规定范围  返回文字
     */
    public function judgeTime(){
        date_default_timezone_set('Asia/Shanghai');
        $HISTime = date ( 'H:i:s' ); // 用户当天起床的时间的 与设置时间做对比
        $WakeStartTime = YII::$app->params['WakeUp']['START'];
        $WakeOverTime = YII::$app->params['WakeUp']['OVER'];
        $sunOffTime = '17:00:00';
        if( $HISTime >= $WakeStartTime && $HISTime < $WakeOverTime){
            // 06:30:00-10:30:00
            return FALSE;
        }else if ($HISTime < $WakeStartTime) {
                // 00:00:00-06:30:00
                return "北鼻,现在离起床还早呢,再睡一会吧!\n";
            } else if ($HISTime >= $WakeOverTime && $HISTime < $sunOffTime) {
                // 10:30:00-17:00:00
                return "北鼻,现在太阳都晒屁股啦!\n起床签到,时间为" . $WakeStartTime . "-" . $WakeOverTime . "\n\n";
            } else {
                // 17:00:00-24:00:00
                return "北鼻,现在太阳都下山啦!\n起床签到,时间为" . $WakeStartTime . "-" . $WakeOverTime . "\n";
            }

    }
    /**
     * [签到的具体时间精确到毫秒]
     * @return [string] [毫秒]
     */
    public function getmsecTime(){

        $comps = explode(' ',  microtime());
        return floatval($comps[0]) * 1000000;
    }

    public function wakeUpSign($morningResult){
        date_default_timezone_set('Asia/Shanghai');
        $YMDTime = date ( 'Y-m-d' );
        //var_dump($YMDTime);
        //var_dump($morningResult['time']);
        if ( $morningResult['time'] >= $YMDTime){
            return TRUE;
        }else{

            return FALSE;
        }
    }
    public function wakeUpContentSign($morningResult){
        date_default_timezone_set('Asia/Shanghai');
        $HISTime = date ( 'H:i:s' );
        $YMDTime = date ( "Y-m-d" );
        $WakeStartTime = YII::$app->params['WakeUp']['START'];
        $WakeOverTime = YII::$app->params['WakeUp']['OVER'];

        if( $morningResult['time'] >= $YMDTime){
            //已经签到
            return FALSE;
        }else{
            if( $HISTime >= $WakeStartTime &&  $HISTime < $WakeOverTime ){
                // 用户当天没有签到，而且在签到范围内
                $this->renderJSON('"北鼻,今天还没和小北说早,赶紧点击‘签到’."');
            }else{
                //用户当天没有签到，而且不在签到范围内
                if($HISTime >= $WakeOverTime ){
                    $this->renderJSON("今天和小北说‘起床’的时间已经过去了.\n起床签到,时间为".$WakeStartTime."-".$WakeOverTime."\n");
                }else if( $HISTime < $WakeStartTime ){
                    $this->renderJSON("今天和小北说‘起床’的时间还没有到.\n起床签到,时间为".$WakeStartTime."-".$WakeOverTime."\n");
                }
            }
        }

    }


    public function yesterdayWakeUpSign($userId){
        $morningResult = BlxbgameMorning::yesterdayIsSignUp($userId);

        if($morningResult){
            return true;//用户昨天签过到
        }else{
            return false;//用户昨天没签到
        }

    }

    public function confirmSignUp($morningResult){

        //数据库没有数据时，确认为第一次签到
        $confirm['firstWakeUp'] = $morningResult == NULL ? TRUE : FALSE;

        //检测是否连续签到
        if($this->yesterdayWakeUpSign($morningResult['userid'])){
            $confirm['signdays'] = ++$morningResult['signdays'] ;
        }else{
            $confirm['signdays'] = 1;
        }

        //增加积分
        date_default_timezone_set('Asia/Shanghai');
        $HISTime = date ( 'H:i:s' ); // 定义时间格式
        if( date("06:30:00") <= $HISTime && $HISTime <= date("06:40:00") ){
            $score = 20;
        }else if( date("06:40:00") < $HISTime && $HISTime <= date("07:30:00") ){
            $score = 18;
        }else if( date("07:30:00") < $HISTime && $HISTime <= date("08:30:00") ){
            $score = 16;
        }else{
            $score = 12;
        }

        //连签加分
        if($confirm['signdays']<=4 && $confirm['signdays'] >=2)
        {
            $point =rand(0,1);
            $score = $score+$point;
        }else if($confirm['signdays']>=5) {
            $score = $score+2;
        }
        //确认加分
        $confirm['totalscore'] = $score;

        if($morningResult != NULL){
            $confirm['totalscore'] =  $morningResult['totalscore']+$confirm['totalscore'];
        }

        return $confirm;

    }




}
